from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from django.core.paginator import Paginator


class CateAPIView(APIView):
    def post(self, request):
        name = request.data.get('name')
        cate_obj = CateModel.objects.filter(name=name)
        if cate_obj:
            return Response({'msg': '该分类已存在', 'code': 400})
        else:
            ser = CateModelSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '添加成功', 'code': 200})
            else:
                return Response({'errors': ser.errors, 'code': 400})

    def get(self, request):
        current_page = request.GET.get('current_page')  # 获取当前页码
        cate_list = CateModel.objects.all()  # 获取所有数据
        paginatoo = Paginator(cate_list, 2)  # 每页展示两条数据
        paged = paginatoo.page(current_page)  # 获取当前页数据
        ser = CateModelSerializer(paged, many=True)
        return Response({
            'page_sum': paginatoo.num_pages,
            'page_list': [i for i in paginatoo.page_range],
            'data': ser.data
        })

    def delete(self, request):
        cate_id = request.data.get('cate_id')
        cate_obj = CateModel.objects.filter(pk=cate_id)
        if cate_obj:
            cate_obj.delete()
            return Response({'msg': '删除成功', 'code': 200})
        else:
            return Response({'msg': '删除失败', 'code': 400})

    def put(self, request):
        cate_id = request.data.get('cate_id')
        cate_obj = CateModel.objects.filter(pk=cate_id).first()
        if cate_obj:
            ser = CateModelSerializer(cate_obj, data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '修改成功', 'code': 200})
            else:
                return Response({'msg': '修改失败', 'code': 400})
        else:
            return Response({'msg': '该分类不存在', 'code': 400})


class GoodsAPIView(APIView):
    def post(self, request):
        name = request.data.get('name')
        if GoodsModel.objects.filter(name=name):
            return Response({'msg': '该商品已存在', 'code': 400})
        ser = GoodsModelserializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response({'errors': ser.errors})

    def get(self, request):
        cate_id = request.GET.get('cate_id')
        cate_obj = CateModel.objects.get(pk=cate_id)
        goods_obj = GoodsModel.objects.filter(cate=cate_obj)
        ser = GoodsModelserializer(goods_obj, many=True)
        return Response(ser.data)


class CateAPIView01(APIView):
    def get(self, request):
        cate_obj = CateModel.objects.all()
        ser = CateModelSerializer(cate_obj, many=True)
        return Response(ser.data)
